import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui' as ui;

import 'package:flutter3demo/CustomRootElement.dart';


void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home:Material(child: TestPage()),
    );
  }
}

class TestPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return TestPageState();
  }

}
class TestPageState extends State<TestPage> {
  List<String> tempList = [];
  int aC = 0;
  List data = [1, 2, 3, 4];



  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return _body();
  }

  /*
  * @override
  void mount(Element? parent, Object? newSlot) {
    super.mount(parent, newSlot);
    final MultiChildRenderObjectWidget multiChildRenderObjectWidget = widget as MultiChildRenderObjectWidget;
    final List<Element> children = List<Element>.filled(multiChildRenderObjectWidget.children.length, _NullElement.instance);
    Element? previousChild;
    for (int i = 0; i < children.length; i += 1) {
      final Element newChild = inflateWidget(multiChildRenderObjectWidget.children[i], IndexedSlot<Element?>(i, previousChild));
      children[i] = newChild;
      previousChild = newChild;
    }
    _children = children;
  }*/
  Widget _body(){
    String textStr = "阿达可视电话阿克苏记得哈" * 4;
    TextStyle style = TextStyle(
      color: Colors.white,
      fontSize: 14,
    );
    return Column(
      key: Key(Random().nextInt(100000000).toString()),
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        GestureDetector(
          key: Key(Random().nextInt(100000000).toString()),
          onTap: (){
            print("asdasdads");
            Flex flex = const Flex(direction: Axis.vertical,);
            flex.createElement();
            BuildOwner? owner = context.owner;
            Column column = Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: List.generate(10, (index) => Container(
                width: 110,
                height: 110,
                color: Color.fromARGB(255, Random().nextInt(255), Random().nextInt(255), Random().nextInt(255)),
              )),
            );











            ///renderTree
            // PipelineOwner pLineowner = View.pipelineOwnerOf(context);
            // renderFlex.attach(pLineowner);

            var a = Container(width: 200,height: 200,padding: const EdgeInsets.all(10),color: Colors.green,);
            // a = column;
            RootWidget rootW =  RootWidget(child:a);
            RenderFlex renderFlex = column.createRenderObject(context);
            MultiChildRenderObjectElement columnElement = column.createElement();


            RootElement rootE = RootElement(rootW);
            // WidgetsBinding.instance.attachRootWidget(rootW);
            //
            WidgetsBinding.instance.wrapWithDefaultView(rootW);
            BuildOwner o = BuildOwner(focusManager: FocusManager());

            RootElement ee = rootW.attach(o,);


            renderFlex.attach(o);



            // ee.assignOwner(o);
            // ee.mount(null,null);

            // RenderObjectToWidgetAdapter a;





            // rootE.inflateWidget(column, null);
            // rootE.assignOwner(o);
            // MultiChildRenderObjectWidget
    // columnElement.markNeedsBuild();


            // adapter.attachToRenderTree(owner);


            // context.owner;






            // final MultiChildRenderObjectWidget multiChildRenderObjectWidget = column;
            // final List<Element> children = [];
            // Element? previousChild;
            // for (int i = 0; i < column.children.length; i += 1) {
            //   final Element newChild = columnElement.inflateWidget(multiChildRenderObjectWidget.children[i], IndexedSlot<Element?>(i, previousChild));
            //   children.add(newChild);
            //   previousChild = newChild;
            // }
            //
            //
            //
            //
            //
            // // ui.FlutterView flutterView = View.of(context);


            // e.mount(flutterView, null);

            ///WidgetTree
            // View view = View(view: flutterView, child: column);

            // view.build(context);






            // RenderObject? renderObject = context.findRenderObject();

            // flutterView.c
            //
            // e.mount(flutterView, null);
            //
            //
            //
            // e.mount(parent, newSlot);

            // e.attachRenderObject(f);
            //
            // RenderObjectToWidgetAdapter adapter = RenderObjectToWidgetAdapter(container: f);




            // RenderObjectToWidgetElement<T> attachToRenderTree(BuildOwner owner, [ RenderObjectToWidgetElement<T>? element ])


            // e.mount(null,null);


            //
            // renderFlex.layout(BoxConstraints(maxWidth: 100,maxHeight: 3000,minHeight: 0,minWidth: 0));
            print("f.size ===");
            print("columnElement.children========${columnElement.children}");
            print("f.size === ${renderFlex.size}");
            // setState(() {
            //
            // });
          },
          child: Container(
            width: 100,
            height: 100,
            color: Color.fromARGB(Random().nextInt(255), Random().nextInt(255), Random().nextInt(255), Random().nextInt(255)),
          ),
        ),
    //       Container(
    //         child: Row(
    //           children: [
    //             Container(
    //               width: 100,
    //               height: 200,
    //               color: Colors.red,
    //               child: Center(
    //                 child: Text(
    //                   textStr,
    //                     style: style,
    //                   textScaleFactor: 1,
    //                 ),
    //               ),
    //             ),
    //             Expanded(
    //               child: Column(
    //                 mainAxisSize: MainAxisSize.max,
    //                 crossAxisAlignment: CrossAxisAlignment.start,
    //                 mainAxisAlignment: MainAxisAlignment.spaceBetween,
    //                 children: [
    //                   GestureDetector(child: Container(color: Colors.red,child: Text("1asdasdasd"),padding: EdgeInsets.all(20),),onTap: (){
    //
    //                     /*
    //                     * RenderFlex(
    //   direction: direction,
    //   mainAxisAlignment: mainAxisAlignment,
    //   mainAxisSize: mainAxisSize,
    //   crossAxisAlignment: crossAxisAlignment,
    //   textDirection: getEffectiveTextDirection(context),
    //   verticalDirection: verticalDirection,
    //   textBaseline: textBaseline,
    //   clipBehavior: clipBehavior,
    // );
    //                     *
    //                     *
    //                     *
    //                     *
    //                     *
    //                     * */
    //                     Column c = Column(
    //                       mainAxisSize: MainAxisSize.min,
    //                       crossAxisAlignment: CrossAxisAlignment.start,
    //                       children: List.generate(10, (index) => Container(
    //                         width: 100,
    //                         height: 100,
    //                         color: Colors.red,
    //                       )),
    //                     );
    //
    //                     RenderFlex f = c.createRenderObject(context);
    //
    //                     // f = RenderFlex(
    //                     //   direction: Axis.vertical,
    //                     //   mainAxisAlignment: MainAxisAlignment.start,
    //                     //   mainAxisSize: MainAxisSize.min,
    //                     //   crossAxisAlignment: CrossAxisAlignment.start,
    //                     //   textDirection: TextDirection.ltr,
    //                     //   verticalDirection: VerticalDirection.down,
    //                     //   textBaseline: TextBaseline.alphabetic,
    //                     //   clipBehavior: Clip.none,
    //                     //   children:
    //                     // );
    //                     f.children
    //                     f.layout(BoxConstraints(maxWidth: 100,maxHeight: 3000,minHeight: 0,minWidth: 0));
    //                     print("f.size === ${f.size}");
    //                     return;
    //                     RichText  text = RichText(
    //                       text: TextSpan(
    //                           text: textStr,
    //                           style: style
    //                         ),
    //                       textAlign: TextAlign.center,
    //                       textDirection: TextDirection.ltr,
    //                       softWrap: true,
    //                       overflow: TextOverflow.clip,
    //                       textScaleFactor: 1,
    //                       textWidthBasis: TextWidthBasis.parent,
    //                       maxLines: 7,
    //                     );
    //
    //                     RenderParagraph p = text.createRenderObject(context);
    //                     p.layout(BoxConstraints(maxWidth: 100,maxHeight: 200,minHeight: 0,minWidth: 0));
    //                     print("p.size=====${p.size}");
    //
    //
    //
    //
    //
    //                     RenderParagraph a = RenderParagraph(
    //                       TextSpan(
    //                         text: textStr,
    //                         style: style
    //                       ),
    //                       textAlign: TextAlign.center,
    //                       textDirection: TextDirection.ltr,
    //                       softWrap: true,
    //                       overflow: TextOverflow.clip,
    //                       textScaleFactor: 1,
    //                       textWidthBasis: TextWidthBasis.parent,
    //                       maxLines: 7,
    //                     );
    //
    //                     a.layout(BoxConstraints(maxWidth: 100,maxHeight: 200,minHeight: 0,minWidth: 0));
    //
    //                     print(a.size);
    //
    //
    //
    //                     // 1:走layout
    //                     // a.performLayout();
    //                     // {
    //                     //     double width = a.computeMinIntrinsicWidth(100);
    //                     //     double height = a.computeMaxIntrinsicHeight(100);
    //                     //
    //                     //     if (width > maxWidth) {
    //                     //       width = maxWidth;
    //                     //     }
    //                     //     print("width==$width==height==$height");
    //                     //
    //                         Size aa = computeTextSize(
    //                             context, 100, textStr, style,
    //                             maxLines: 7, fixWidth: 0);
    //                         print("aa==$aa");
    //                     //   }
    //                     },),
    //                   Text("3"),
    //                 ],
    //               ),
    //             ),
    //           ],
    //         ),
    //       ),
      ],
    );
  }
  /// 计算文本的size
  Size computeTextSize(context, double maxWidth, String value, TextStyle textStyle,
      {int maxLines = 1, double fixWidth = 2.0, double fixHeight = 0.0}) {
    //很迷的bug，这行代码不要动
    value = value.replaceAll('/', '*').replaceAll('-', ',');

    TextPainter painter = TextPainter(
      ///AUTO：华为手机如果不指定locale的时候，该方法算出来的文字高度是比系统计算偏小的。
      locale: WidgetsBinding.instance.window.locale,
      maxLines: maxLines,
      textDirection: ui.TextDirection.ltr,
      //字体缩放大小
      textScaleFactor: MediaQuery.of(context).textScaleFactor,
      text: TextSpan(text: value, style: textStyle),
    );
    painter.layout(maxWidth: maxWidth);

    ///文字的宽度:painter.height
    return Size(painter.width + fixWidth, painter.height + fixHeight);
  }
}
